package com.system.reflect.demo01;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.PrivilegedExceptionAction;

/**
 * @author DELL
 */
public class ReflectServiceImpl {
    /**
     * 通过反射配置信息构建对象
     * @return object
     */
    public ReflectServiceImpl getInstance(){
    ReflectServiceImpl object = null;
        try {
            object =(ReflectServiceImpl) Class.forName("com.system.reflect.demo01.ReflectServiceImpl").newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return object;
    }
    /**
     * 反射生成对象
     * @param name
     */
    public void sayHello(String name){
        System.out.println("Hello"+ name);

    }
    /**
     * 获取和反射方法
     */
    public Object reflectMethod(){
        Object returnObj = null;
        ReflectServiceImpl target = new ReflectServiceImpl();
        try {
            Method method = ReflectServiceImpl.class.getMethod("sayHello", String.class);
            returnObj = method.invoke(target,"张三");
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            ex.printStackTrace();
        }
        return returnObj;
    }
    /**
     * 反射生成对象和反射调度方法
     * @return object
     */
    public Object reflect(){
        ReflectServiceImpl object = null;
        try {
            object = (ReflectServiceImpl) Class.forName("com.system.reflect.demo01.ReflectServiceImpl").newInstance();
            Method method = object.getClass().getMethod("sayHello", String.class);
            method.invoke(object,"张三");
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException | InstantiationException e) {
            e.printStackTrace();
        }
        return object;
    }
}
